import cv2
import numpy
import utils


def stroke_edges(src, dst, blur_k_size=7, edge_k_size=5):
    if blur_k_size >= 3:
        blurred_src = cv2.medianBlur(src, blur_k_size)  # 先进行模糊化
        gray_src = cv2.cvtColor(blurred_src, cv2.COLOR_BGR2GRAY)  # 生成灰度图像
    else:
        gray_src = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)  # 生成灰度图像
    cv2.Laplacian(gray_src, cv2.CV_8U, gray_src, ksize=edge_k_size)  # 拉普拉斯边缘检测函数
    normalized_inverse_alpha = (1.0 / 255) * (255 - gray_src)  # 进行归一化
    channels = cv2.split(src)  # 将图像的彩色通道分离
    for channel in channels:
        channel[:] = channel * normalized_inverse_alpha
    cv2.merge(channels, dst)  # 将彩色通道拼合成图像


class VConvolutionFilter(object):
    """A filter that applies a convolution to V (or all of BGR)"""

    def __init__(self, kernel):
        self._kernel = kernel

    def apply(self, src, dst):
        """Apply the filter with a BGR or gray source/destination."""
        cv2.filter2D(src, -1, self._kernel, dst)


class SharpenFilter(VConvolutionFilter):
    """A sharpen filter with a 1-pixel radius."""

    def __init__(self):
        kernel = numpy.array(
            [[-1, -1, -1],
             [-1,  9, -1],
             [-1, -1, -1]]
        )
        VConvolutionFilter.__init__(self, kernel)


class FindEdgesFilter(VConvolutionFilter):
    """An edge-finding filter with a 1-ixel radius."""

    def __init__(self):
        kernel = numpy.array(
            [[-1, -1, -1],
             [-1,  8, -1],
             [-1, -1, -1]]
        )
        VConvolutionFilter.__init__(self, kernel)


class BlurFilter(VConvolutionFilter):
    """A blur filter with a 2-pixel radius."""

    def __init__(self):
        kernel = numpy.array(
            [[0.04, 0.04, 0.04, 0.04, 0.04],
             [0.04, 0.04, 0.04, 0.04, 0.04],
             [0.04, 0.04, 0.04, 0.04, 0.04],
             [0.04, 0.04, 0.04, 0.04, 0.04],
             [0.04, 0.04, 0.04, 0.04, 0.04]]
        )
        VConvolutionFilter.__init__(self, kernel)


class EmbossFilter(VConvolutionFilter):
    """An emboss filter with a 1-pixel radius."""

    def __init__(self):
        kernel = numpy.array(
            [[-2, -1,  0],
             [-1,  1,  1],
             [ 0,  1,  2]]
        )
        VConvolutionFilter.__init__(self, kernel)

